package com.itheima.ydd.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.R;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.SysMenuDto;
import com.itheima.ydd.dto.SysRoleDto;
import com.itheima.ydd.entity.SysMenu;
import com.itheima.ydd.entity.SysRole;
import com.itheima.ydd.entity.SysRoleMenu;
import com.itheima.ydd.service.ISysMenuService;
import com.itheima.ydd.service.ISysRoleMenuService;
import com.itheima.ydd.service.ISysRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author author
 * @since 2022-05-22
 */
@RestController
@RequestMapping("/sys_role")
@Slf4j
public class SysRoleController {
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private ISysRoleMenuService sysRoleMenuService;
    @Autowired
    private ISysMenuService sysMenuService;

    @GetMapping("/list")
    public R page(int page, int limit, String name) {
        Map map = new HashMap();
        Page<SysRole> pageInfo = new Page<>(page, limit);
        LambdaQueryWrapper<SysRole> lqw = new LambdaQueryWrapper<>();
        lqw.like(name != null, SysRole::getName, name);
        sysRoleService.page(pageInfo, lqw);


        List<SysRole> sysRoles = pageInfo.getRecords();
        List<SysRoleDto> sysRoleDtos = sysRoles.stream().map(item -> {
            SysRoleDto dto = new SysRoleDto();
            BeanUtils.copyProperties(item, dto);

            LambdaQueryWrapper<SysRoleMenu> lqw2 = new LambdaQueryWrapper<>();
            lqw2.eq(SysRoleMenu::getRoleId, item.getId());
            List<SysRoleMenu> list = sysRoleMenuService.list(lqw2);
            StringBuilder menuIds = new StringBuilder();
            for (SysRoleMenu sysRoleMenu : list) {
                String roleMenuId = sysRoleMenu.getMenuId();
                menuIds.append(menuIds.length() == 0 ? roleMenuId : "," + roleMenuId);
            }
//            dto.setRoleMenus(menuIds.toString());
//            dto.setRoleId(item.getId());
            return dto;

        }).collect(Collectors.toList());

        map.put("totalPages", pageInfo.getPages());
        map.put("currentPage", pageInfo.getCurrent());
        map.put("pageSize", pageInfo.getSize());
        map.put("count", pageInfo.getTotal());
        map.put("data", sysRoleDtos);

        return new R(map, "", 0);


    }

    //新增
    @PostMapping("/add")
    public R save(@RequestBody SysRoleDto sysRoleDto) {
        System.err.println(sysRoleDto);
        System.err.println(sysRoleDto.getName());
        SysRole sysRole = new SysRole();
        String id = UUID.randomUUID().toString();
        sysRole.setId(id);
        BeanUtils.copyProperties(sysRoleDto, sysRole);
        sysRole.setCreateDate(LocalDateTime.now());
        sysRole.setDelFlag("0");
        sysRole.setSuperadmin(0);
        System.err.println(sysRole);
        //将本体保存到sys_role表
        sysRoleService.save(sysRole);
        //获取所有菜单id集合
        Integer[] menuIds = sysRoleDto.getMenuIds();
        //创建空菜单集合
        List<SysRoleMenu> sysRoleMenus = new ArrayList<>();

        for (Integer menuId : menuIds) {
            //创建角色菜单对象
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
//            sysRoleMenu.setRoleId(sysRoleDto.getRoleId());
            sysRoleMenu.setMenuId(menuId + "");
            sysRoleMenus.add(sysRoleMenu);
        }
        sysRoleMenuService.saveBatch(sysRoleMenus);

        return R.success("", "");

    }


    /*//修改
    @PostMapping("/update")
    public R update(@RequestBody SysRole sysRole)
    {
        sysRoleService.updateById(sysRole);
        return  R.success("","");
    }*/

    @PostMapping("/update")
    public R update(@RequestBody SysRoleDto sysRoleDto) {

        //在sys_role修改本体
        sysRoleService.updateById(sysRoleDto);

        Integer[] menuIds = sysRoleDto.getMenuIds();

        String roleId = sysRoleDto.getId();

        //删除role_menu表中对应数据
        LambdaQueryWrapper<SysRoleMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRoleMenu::getRoleId, roleId);
        sysRoleMenuService.remove(wrapper);

        //重新保存
        List<SysRoleMenu> sysRoleMenus = new ArrayList<>();
        for (Integer menuId : menuIds) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRoleId(roleId);
            sysRoleMenu.setMenuId(menuId + "");
            sysRoleMenus.add(sysRoleMenu);
        }

        sysRoleMenuService.saveBatch(sysRoleMenus);

        return R.success("", "");

    }


    //数据回显

    @GetMapping("/rowInfo")
    public ResultData rowInfo(SysRole sysRole) {

        //获取sys_role的角色
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRole::getId, sysRole.getId());
        SysRole sysRole1 = sysRoleService.getOne(wrapper);

        SysRoleDto sysRoleDto = new SysRoleDto();
        BeanUtils.copyProperties(sysRole1, sysRoleDto);

        //获取角色id对应的菜单id集合
        LambdaQueryWrapper<SysRoleMenu> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(SysRoleMenu::getRoleId, sysRole.getId());
        List<SysRoleMenu> sysRoleMenus = sysRoleMenuService.list(wrapper1);

        //遍历集合,获取一级菜单和其子菜单
        List<SysMenu> sysMenus = new ArrayList<>();
        for (SysRoleMenu sysRoleMenu : sysRoleMenus) {

            LambdaQueryWrapper<SysMenu> wrapper2 = new LambdaQueryWrapper<>();
            //只要一级菜单
            wrapper2.eq(SysMenu::getPid, 0);
            wrapper2.eq(SysMenu::getId, sysRoleMenu.getMenuId());

            SysMenu sysMenu = sysMenuService.getOne(wrapper2);

            sysMenus.add(sysMenu);

        }
        sysRoleDto.setAuthLis(sysMenus);

        Map map = new HashMap();
        map.put("data", sysRoleDto);

        return new ResultData(0, "", map);

    }


    //删除
    @GetMapping("/del")
    public R delete(String id) {
        LambdaQueryWrapper<SysRole> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysRole::getId, id);
        sysRoleService.remove(lqw);
        return R.success("", "");


    }

    @GetMapping("/allData")
    public ResultData getAllData() {

        List<SysRole> sysRoles = sysRoleService.list();

        return new ResultData(0, "", sysRoles);

    }


}
